//
//  XCStatusViewModel.swift
//  小陈微博Swift用纯代码创建
//
//  Created by 小陈 on 16/3/2.
//  Copyright © 2016年 小陈. All rights reserved.
//

import UIKit
import SDWebImage
class XCStatusViewModel: NSObject {

     func loadUserStatus(since_id: Int, max_id: Int,loadStatusCallBack:(statusResult:[XCStatus]?, error: NSError?) ->()){

        XCNetworkingTool.sharedInstance.loadStatus(since_id, max_id: max_id) { (result, error) -> () in
            
        
//        XCNetworkingTool.sharedInstance.loadStatus { (result, error) -> () in
            if error != nil{
                print("XCStatusViewModel ： 加载用户数据失败\(error)")
                loadStatusCallBack(statusResult: nil, error: error)
                return
            }
            
            // 判断数组是字典数组 不是就返回空
            if let TempArr = result?["statuses"] as? [[String: AnyObject]]{
              
                // 定义了一个空数组
                var statusTemp = [XCStatus]()
                
                for dict in TempArr {
                  
                    let status = XCStatus(dict: dict)
                    statusTemp.append(status)
                }
                
               self.loadWebImage(statusTemp, loadStatusCallBack: loadStatusCallBack)
//                // 加载数据成功
//                 loadStatusCallBack(statusResult: statusTemp, error: nil)
            }else{
                loadStatusCallBack(statusResult: nil, error: nil)
            }
            
        }
        
    }
    
    func loadWebImage(statuses:[XCStatus],loadStatusCallBack:(statusResult:[XCStatus]?, error: NSError?) ->()){
        var length = 0
        let group = dispatch_group_create()
        print("图片缓存的地址为\(NSHomeDirectory())")
        
        for status in statuses {
            var urls:[NSURL] = [NSURL]()

            if let downLoadURL = status.storePictureURLs{
                urls = downLoadURL
            }
            
            if let downLoadURL = status.retweeted_status?.storePictureURLs{
                urls = downLoadURL
            }
            if urls.count == 1{
                let url = urls.first
                dispatch_group_enter(group)
//                SDWebImageManager.sharedManager().downloadWithURL(url, options: [], progress: nil, completed: { (image, error, _, _) -> Void in
//                    
//                })
                
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image,error, _, _, _) -> Void in
                    dispatch_group_leave(group)
                    if error != nil{
                        print("加载失败")
                        return
                    }

                    
                  let date =   UIImagePNGRepresentation(image)
//                    let date = UIImagePNGRepresentation(image)
                    length += date!.length
                    
                })
                
                
            }
            
        }
//---------------出错的地方就是下载图片是在for循环里面--导致下拉刷新的时没有结束刷新-----------------
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            print("图片加载完成缓存的图片的大小为\(CGFloat(length) / 1024.0 / 1024.0)MB)")
            // 加载数据成功
            loadStatusCallBack(statusResult: statuses, error: nil)
        })
    }
    
    
    
    /// 发微博
  class  func sendStatus(status:String,sendStatusBackCall:(error:NSError?)->()){
        guard let access_token = XCUSerAccountViewModel.sharedInstance.userAccount?.access_token  else{
            print("access_Token 没有值")
            return
        }
        
        let parameter = [
            "access_token": access_token,
            "status": status
        ]
        let url = "https://api.weibo.com/2/statuses/update.json"
        
        XCNetworkingTool.sharedInstance.afnManager.POST(url, parameters: parameter, progress: nil, success: { (_, result) -> Void in
            sendStatusBackCall(error: nil)
            // 发送微博成功
            }) { (_, error) -> Void in
//                发送微博失败
                sendStatusBackCall(error: error)
        }
        
        
        
    }
    
    
}
